package cn.year9;

import org.ho.yaml.Yaml;
import org.ho.yaml.YamlDecoder;
import org.ho.yaml.YamlEncoder;
import org.ho.yaml.YamlOperations;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


public class TdbHandle {
    File file = new File("Data.tdb");
    //验证用户身份

    public boolean UserValidate(String user,String password)
    {
        TdbBase[] tdbdao = this.openDatabase();
        int flag = this.contactTdbtest();

        if (tdbdao[flag].getField().get("puser").equals(user) && tdbdao[flag].getField().get("Enppassword").equals(password))
        {
            return true;
        }
        return false;
    }

    //程序运行判断数据库文件是否存在
    public boolean TdbExist()
    {
        if (!file.exists())
        {
            return false;
        }
        return true;
    }

    //数据库链接
    public TdbBase[] openDatabase()
    {
        if (!TdbExist())
        {
            return null;
        }

        YamlDecoder dec = null;
        try {
            dec = new YamlDecoder(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        int count=0;
        while(true){
            try{
                dec.readObject();
                count++;
            }catch(EOFException e){
                break;
            }
        }

        dec.close(); //释放指针

        try {
            dec = new YamlDecoder(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            return null;
        }


        TdbBase[] base = new  TdbBase[count];

        for (int i=0;i<count;i++)
        {
            try {
                base[i]  = (TdbBase) dec.readObject();
            } catch (EOFException e) {
                return null;
            }
        }

        dec.close();//释放指针

        return base;
    }

    //管理员表创建
    public boolean createTdb(String puser,String Enppassword, String EnTdbPassword)
    {
        TdbBase admin = new TdbBase("admin");
        admin.setIndex("0");
        admin.setItemNum("4");
        admin.setCreateTime(new Date().toString());
        Map<String,String> item = new HashMap<>();
        item.put("puser",puser);
        item.put("Enppassword",Enppassword);
        item.put("EnTdbPassword",EnTdbPassword);
        item.put("flag","1");
        admin.setField(item);
        try {
            Yaml.dump(admin,file);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    //数据库链接校验
    public Integer contactTdbtest()
    {

        TdbBase[] tdbdao = this.openDatabase();
        int flag;
        for (int i=0;i<tdbdao.length;i++)
        {
            if(!tdbdao[i].getTable().equals("admin"))
            {
                return 404;
            }else{
                flag = i;
            }

            if(tdbdao[flag].getField().get("flag").equals("1"))
            {
                return flag;
            }
        }

        return 500;
    }




    //新建表
    public boolean createTable(String TableName,String count,Map<String,String> tablefield)
    {
        TdbBase table = new TdbBase(TableName);
        table.setIndex(String.valueOf(getNewTableId() + 1));
        table.setItemNum(count);
        table.setCreateTime(new Date().toString());
        table.setField(tablefield);
        try {
            YamlEncoder encoder = new YamlEncoder(new FileOutputStream(file,true));
            encoder.writeObject(table);
            encoder.flush();
            encoder.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }


    //获取最新的自增值
    public Integer getNewTableId()
    {
        TdbBase[] tdbdao = this.openDatabase();
        int max = Integer.valueOf(tdbdao[0].getIndex());
        for (int i=0;i<tdbdao.length;i++)
        {
            if (max < Integer.valueOf(tdbdao[i].getIndex()))
            {
                max = Integer.valueOf(tdbdao[i].getIndex());
            }
        }
        return max;
    }


    //写入字段


    //更新表


    //删除表
    public boolean removeTable(int index) {
        if (index == 0)
        {
            Message message = new Message();
            message.send(MessageType.Warning,"无法删除基础管理员表...\n");
            return false;
        }
        TdbBase[] tdbBases = openDatabase();
        try {
            file.delete();
            YamlEncoder yamlEncoder = new YamlEncoder(new FileOutputStream(file,true));
            ArrayList<Object> arrayList = new ArrayList<>();

            for (int i=0;i<tdbBases.length;i++)
            {
                if (Integer.valueOf(tdbBases[i].getIndex()) != index)
                {
                    arrayList.add(tdbBases[i]);
                }
            }

            for (int i=0;i<arrayList.size();i++)
            {
                yamlEncoder.writeObject(arrayList.get(i));
            }

            yamlEncoder.flush();
            yamlEncoder.close();

            return true;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }

    }

    //查询表
    public TdbBase searchTable(Integer TableIndex)
    {
        TdbBase[] reslut = openDatabase();
        for (int i=0;i<reslut.length;i++)
        {
            if (Integer.valueOf(reslut[i].getIndex()) == TableIndex)
            {
                return reslut[i];
            }
        }
        return null;
    }

    //重命名表
    public boolean renameTable(Integer TableIndex,String newName)
    {
        if (TableIndex == 0) {
            Message message = new Message();
            message.send(MessageType.Warning, "无法更改基础管理员表...\n");
            return false;
        }
        TdbBase[] tdbBases = openDatabase();
        file.delete();
        try {
            YamlEncoder yamlEncoder = new YamlEncoder(new FileOutputStream(file,true));
            ArrayList<Object> arrayList = new ArrayList<>();

            for (int i=0;i<tdbBases.length;i++)
            {
                if (Integer.valueOf(tdbBases[i].getIndex()) == TableIndex)
                {
                    tdbBases[i].setTable(newName);
                }
                arrayList.add(tdbBases[i]);
            }

            for (int i=0;i<arrayList.size();i++)
            {
                yamlEncoder.writeObject(arrayList.get(i));
            }

            yamlEncoder.flush();
            yamlEncoder.close();

            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }

    }


}
